

package com.zoespeer.food_delivery_comment_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zoespeer.food_delivery_comment_api.common.exception.UserException;
import com.zoespeer.food_delivery_comment_api.entity.Category;
import com.zoespeer.food_delivery_comment_api.entity.Restaurant;
import com.zoespeer.food_delivery_comment_api.entity.User;
import com.zoespeer.food_delivery_comment_api.mapper.CategoryMapper;
import com.zoespeer.food_delivery_comment_api.mapper.RestaurantMapper;
import com.zoespeer.food_delivery_comment_api.mapper.UserMapper;
import com.zoespeer.food_delivery_comment_api.service.RestaurantService;
import com.zoespeer.food_delivery_comment_api.vo.AddCanteenVO;
import com.zoespeer.food_delivery_comment_api.vo.CanteenDetailRequestVO;
import com.zoespeer.food_delivery_comment_api.vo.CanteenDetailVO;
import com.zoespeer.food_delivery_comment_api.vo.RestaurantListRequestVO;
import com.zoespeer.food_delivery_comment_api.vo.RestaurantVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;

@Service
public class RestaurantServiceImpl implements RestaurantService {

    // 新增：注入分类Mapper，用于查询分类ID
    private final CategoryMapper categoryMapper;
    private final RestaurantMapper restaurantMapper;
    private final UserMapper userMapper;

    // 构造方法注入：补充CategoryMapper依赖
    @Autowired
    public RestaurantServiceImpl(RestaurantMapper restaurantMapper,
                                 UserMapper userMapper,
                                 CategoryMapper categoryMapper) {
        this.restaurantMapper = restaurantMapper;
        this.userMapper = userMapper;
        this.categoryMapper = categoryMapper; // 新增注入
    }

    /**
     * 获取餐厅列表（分页+搜索）
     */
    @Override
    public IPage<RestaurantVO> getRestaurantList(RestaurantListRequestVO request) {
        // 校验分页参数合法性
        if (request.getPageNum() < 1) {
            throw new UserException("页码不能小于1");
        }
        if (request.getPageSize() < 1 || request.getPageSize() > 100) {
            throw new UserException("每页数量必须在1-100之间");
        }

        Page<RestaurantVO> page = new Page<>(request.getPageNum(), request.getPageSize());
        return restaurantMapper.getRestaurantList(page, request);
    }

    /**
     * 获取餐厅详情（含评论）
     */
    @Override
    public CanteenDetailVO getCanteenDetail(CanteenDetailRequestVO request) {
        if (request.getCanteenId() == null || request.getCanteenId() < 1) {
            throw new UserException("餐厅ID不能为空且必须为正数");
        }
        CanteenDetailVO detail = restaurantMapper.getCanteenDetail(request);
        if (detail == null) {
            throw new UserException("餐厅不存在");
        }
        return detail;
    }

    /**
     * 添加餐厅（核心逻辑完善）
     */
    @Override
    public Restaurant addCanteen(AddCanteenVO addCanteenVO) {
        // 1. 校验用户ID有效性
        Integer userId;
        try {
            userId = Integer.parseInt(addCanteenVO.getUserId().trim());
        } catch (NumberFormatException e) {
            throw new UserException("用户ID必须为数字");
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new UserException("用户不存在");
        }

        // 2. 校验核心参数
        if (!StringUtils.hasText(addCanteenVO.getCanteenName())) {
            throw new UserException("餐厅名称不能为空");
        }
        if (!StringUtils.hasText(addCanteenVO.getPart())) {
            throw new UserException("分类（part）不能为空");
        }
        if (!StringUtils.hasText(addCanteenVO.getAddress())) {
            throw new UserException("地址不能为空");
        }
        if (addCanteenVO.getCost() == null || addCanteenVO.getCost().doubleValue() < 0) {
            throw new UserException("人均消费不能为负数");
        }
        if (!StringUtils.hasText(addCanteenVO.getPicture())) {
            throw new UserException("图片URL不能为空");
        }

        // 3. 处理图片URL：拆分主图和附图（原生JSON拼接）
        String[] pictureUrls = addCanteenVO.getPicture().trim().split(",");
        if (pictureUrls.length == 0) {
            throw new UserException("图片URL格式错误（至少包含一个URL）");
        }
        String mainImage = pictureUrls[0]; // 主图
        // 拼接附图为JSON数组
        StringBuilder imagesJsonBuilder = new StringBuilder("[");
        if (pictureUrls.length > 1) {
            for (int i = 1; i < pictureUrls.length; i++) {
                imagesJsonBuilder.append("\"").append(pictureUrls[i].trim()).append("\"");
                if (i != pictureUrls.length - 1) {
                    imagesJsonBuilder.append(",");
                }
            }
        }
        imagesJsonBuilder.append("]");
        String imagesJson = imagesJsonBuilder.toString();

        // 4. 查询分类ID（解决外键约束问题）
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName, addCanteenVO.getPart().trim());
        Category category = categoryMapper.selectOne(queryWrapper);
        if (category == null) {
            throw new UserException("分类不存在，请检查part参数（当前分类：" + addCanteenVO.getPart() + "）");
        }

        // 5. 封装餐厅实体
        Restaurant restaurant = new Restaurant();
        restaurant.setName(addCanteenVO.getCanteenName().trim());
        restaurant.setCategoryId(category.getCategoryId()); // 关联有效的分类ID
        restaurant.setMainImage(mainImage);
        restaurant.setImages(imagesJson);
        restaurant.setAddress(addCanteenVO.getAddress().trim());
        restaurant.setDescription(StringUtils.hasText(addCanteenVO.getContent())
                ? addCanteenVO.getContent().trim()
                : null);
        restaurant.setAvgPrice(addCanteenVO.getCost());
        restaurant.setApplicantId(userId);
        restaurant.setApplicantNote(StringUtils.hasText(addCanteenVO.getReason())
                ? addCanteenVO.getReason().trim()
                : null);
        restaurant.setStatus("pending"); // 默认为待审核状态
        restaurant.setCreatedAt(LocalDateTime.now());
        restaurant.setUpdatedAt(LocalDateTime.now());

        // 6. 插入数据库
        int rows = restaurantMapper.insert(restaurant);
        if (rows <= 0) {
            throw new UserException("添加餐厅失败，请重试");
        }

        return restaurant;
    }
}